package cn.guozeyiblog.client;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import net.youmi.android.banner.AdSize;
import net.youmi.android.banner.AdView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import cn.guozeyiblog.blogutils.BlogUtils;
import cn.guozeyiblog.blogutils.FileUtils;
import cn.guozeyiblog.netutils.HttpUtil;
import cn.guozeyiblog.netutils.JsoupUtils;
import cn.guozeyiblog.netutils.NetWorkStatus;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

public class ArticleDetailActivity extends Activity implements OnClickListener {
	private Intent intent;
	private ProgressBar loadbar;
	private ListView mlistview;
	private ImageView backButton;
	private ImageView shareButton;
	private ArrayList<BlogUtils> mArrayList;
	private ArticleDetailAdapter adapter;
	private Context context;
	private TextView tv_titleTextView;
	private String Articleurl="http://guozeyiblog.cn/?post=40";
	private DisplayImageOptions options;
	private ImageLoader imageLoader;
	private LinearLayout adlayout;
	private Handler Handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			//消息处理
			adapter.notifyDataSetChanged();
			for (BlogUtils b:mArrayList) {
				System.out.println(b.getContent());
			}
			loadbar.setVisibility(View.GONE);
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.article_detail_activity);
		initView();
		//-------------------------------------------------------------------------------------
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(ArticleDetailActivity.this));
		//-------------------------------------------------------------------------------------
		intent = getIntent();
		Articleurl = intent.getStringExtra("url");
		this.context = getApplicationContext();
		
		tv_titleTextView.setText(getResources().getString(R.string.article_detail));
		//--------------------------------------------------------
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.album_thumb_default)
		.showImageForEmptyUri(R.drawable.album_thumb_default)
		.showImageOnFail(R.drawable.album_thumb_default)
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.considerExifParams(true)
		.displayer(new RoundedBitmapDisplayer(20))
		.build();
		//---------------------------------------------------------
		mArrayList = new ArrayList<BlogUtils>();
		adapter = new ArticleDetailAdapter();
		mlistview.setAdapter(adapter);
		//-----------------------AD--------------------------------
		AdView adView = new AdView(getApplicationContext(), AdSize.FIT_SCREEN);
		adlayout.addView(adView);
		
		mlistview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				//跳转到图片预览页面
				//Toast.makeText(getApplicationContext(), "You Click Image", 0).show();
				Intent intent = new Intent(ArticleDetailActivity.this, ImageActivity.class);
				intent.putExtra("URL", mArrayList.get(position).getContent());
				startActivity(intent);
			}
		});
		//请求网络
		if(NetWorkStatus.isNetworkAvailable(getApplicationContext())){
			new GetArticleDetail().execute(Articleurl);
		}else {
			Toast.makeText(getApplicationContext(), "你的网络不可用哦", 0).show();
		}
		
		backButton.setEnabled(true);
		shareButton.setEnabled(true);
		backButton.setOnClickListener(this);
		shareButton.setOnClickListener(this);
	}
	
	private void initView(){
		backButton = (ImageView) findViewById(R.id.head_back);
		shareButton = (ImageView) findViewById(R.id.head_share);
		loadbar = (ProgressBar) findViewById(R.id.load_article_bar);
		mlistview = (ListView) findViewById(R.id.article_detail_list);
		tv_titleTextView = (TextView) findViewById(R.id.head_title);
		adlayout = (LinearLayout) findViewById(R.id.adLayout);
	}
	
	public class GetArticleDetail extends AsyncTask<String, Void, Void>{

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			//获取网络数据
			String result = HttpUtil.httpGet(params[0]);
			try {
				mArrayList = JsoupUtils.GetArticleList(result);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Handler.sendMessage(Handler.obtainMessage());//通知获取数据完毕
		}
		
	}
	
	/**
	 * 适配器
	 * @author kutear
	 *
	 */
	public class ArticleDetailAdapter extends BaseAdapter{
		
		public ArticleDetailAdapter() {
			// TODO Auto-generated constructor stub
		}
		
		@Override
		public boolean areAllItemsEnabled() {
			// TODO Auto-generated method stub
			return false;
		}
		
		@Override
		public boolean isEnabled(int position) {
			// TODO Auto-generated method stub
			//对指定的ｉｔｅｍ可以点击,只允许图片视频可以点击
			if (mArrayList.get(position).getBlogtype()==BlogUtils.DEF_BLOG_ITEM_TYPE.IMG
					||mArrayList.get(position).getBlogtype()==BlogUtils.DEF_BLOG_ITEM_TYPE.FLASH) {
				return true;
			}else {
				return false;
			}
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mArrayList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			//List item
			LinearLayout layout = null;
			ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
			switch (mArrayList.get(position).getBlogtype()) {
			case BlogUtils.DEF_BLOG_ITEM_TYPE.TITLE:
				layout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.article_title, null);
				TextView title = (TextView) layout.findViewById(R.id.article_detail_title);
				title.setText(mArrayList.get(position).getContent());
				break;
			case BlogUtils.DEF_BLOG_ITEM_TYPE.CONTENT:
				layout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.article_text, null);
				TextView content = (TextView) layout.findViewById(R.id.article_detail_text);
				content.setText(mArrayList.get(position).getContent());
				break;
			case BlogUtils.DEF_BLOG_ITEM_TYPE.CODE:
				layout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.article_code, null);
				WebView code = (WebView) layout.findViewById(R.id.article_detail_code);
				//加载代码段
				code.getSettings().setJavaScriptEnabled(true);
				String code_pl = FileUtils.getFileContent(getApplicationContext(), "code.html");
				String html = code_pl.replace("{{CODE}}", mArrayList.get(position).getContent());
				code.loadDataWithBaseURL("file:///android_asset/", html,
						"text/html", "utf-8", null);
				break;
			case BlogUtils.DEF_BLOG_ITEM_TYPE.IMG:
				System.out.println("----------------------------IMG---------------------------");
				layout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.article_image, null);
				ImageView image = (ImageView) layout.findViewById(R.id.article_detail_image);
				
				
				System.out.println("Image---URL:"+mArrayList.get(position).getContent());
				imageLoader.displayImage(mArrayList.get(position).getContent(), image, options, animateFirstListener);
				
				
				break;
			case BlogUtils.DEF_BLOG_ITEM_TYPE.FLASH:
				layout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.article_flash, null);
				VideoView video = (VideoView) layout.findViewById(R.id.article_detail_video);
				break;

			default:
				layout = new LinearLayout(getApplicationContext());
				break;
			}
			return layout;
		}
		
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.head_back:
			finish();
			break;
		case R.id.head_share:
			//Toast.makeText(getApplicationContext(), "分享功能", 0).show();
			  Intent intent=new Intent(Intent.ACTION_SEND);      
		      intent.setType("text/plain");
		      intent.putExtra(Intent.EXTRA_SUBJECT,"文章分享");
		      intent.putExtra(Intent.EXTRA_TEXT, "我在这里看见一篇好文章,特意推荐给你看看,"+Articleurl);
		      startActivity(Intent.createChooser(intent, getTitle()));
			
			break;

		default:
			break;
		}
	}
	
	
	//--------------------------------------------------------------------------------
	private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

		static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
			Log.v("APP", "加 载 完 成");
			
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}
}
